<?php

class SucursalesController extends Controller
{

	public function actions()
	{
		//return array();
	}

	function get_data($url)
	{
	
		$data = Yii::app()->cache->get('url');
		
		if(isset($data) && $data !== NULL && strlen($data) > 0) {
			//echo("Reading $url from cache");
		} else {
			$data = file_get_contents($url);
			Yii::app()->cache->set('url', $data, 60 * 60 ); 
			
			//echo('Setting cache value for $url');	
		}
	
		return $data;
	}
		
	public function actionIndex(){
		return $this->actionJson();
	}
	
	
	public function actionJson(){

		$dgid = FALSE;
		
		if(isset ($_GET['dgid'])) {
			$dgid = $_GET['dgid'];			
		}
		
		$this->layout = false;
		
		$url = 'http://megatlon.com/js/sedes_mapa.php';
		//$url = "data.php";
		
		$file = $this->get_data($url);
		
		$output = '';
		$pre = '';
		$post = '';
		
		if( strlen($file) == 0) {
			$pre = "{\"sucursales\":[";
			$post = "],\"grillaHoraria\":[],\"stamp\":\"". date('c') ."\"}";
			$output .= utf8_encode($pre);
			$output .= utf8_encode($post);
		} else {
			$istart = strpos($file,"[{");
			
			$file = substr($file, $istart);
			$istart = strpos($file,"];");
			
			$len = strlen($file);
			$file = substr($file, 0, -($len - $istart) + 1);
			
			$pre = "{\"sucursales\":";
			$post = "]}";
			
			$output .= utf8_encode($pre);
			$output .= substr( $file, 0 , -2);
			
			$output .= utf8_encode($post);
			
			$jsonString = json_decode( $output, true);
			
			$grids = array();
			$sucursales = $jsonString['sucursales'];
						
			$helper = new NlpHorario();
			
			foreach($sucursales as $suc){
				
				//echo "suc ".$suc['id'].' horario : '.$suc['horario']. " \n";
				
				$grid = $helper->grillaHoraria($suc['horario']);
		
				if(sizeof($grid) > 0){
					$grids['s='.$suc['id']] = $grid;
				}	
			}
			
			$output = '';
			$jsonStringGrilla = json_encode($grids);
			$output .= utf8_encode($pre);
			$output .= substr( $file, 0 , -2);
			$output .= '],"grillaHoraria":[' . $jsonStringGrilla;
			$output .= utf8_encode('],"stamp":"'. date('c') .'"}');
			
		}
		
		$output = preg_replace("/&quot;/", "", $output);
		$output = preg_replace("/&nbsp;/", " ", $output);

		if ($dgid === FALSE) {
		
		} else {

			$log = array();
			$log['url'] = $_SERVER['REQUEST_URI'];
			$log['agent'] = $_SERVER['HTTP_USER_AGENT'];
			$log['ip'] = $this->getRealIpAddr();
		
			$logjosn = json_encode($log);

			$accessLog = new AccessLog();
			$accessLog->save($logjosn,$dgid);
		}

		$this->render('json',array('output'=>$output));

	}
	
	
	function getRealIpAddr()
	{
	    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
	    {
	      $ip=$_SERVER['HTTP_CLIENT_IP'];
	    }
	    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
	    {
	      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	    }
	    else
	    {
	      $ip=$_SERVER['REMOTE_ADDR'];
	    }
	    return $ip;
	}


}